package com.zz.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.zz.dto.ResponseResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class VcodeController {
    char[] vcodeSequence = {'0','1','2','3','4','5','6','7','8','9'};

    @RequestMapping("/vcode")
    public void vcode(HttpServletResponse resp, HttpServletRequest req) throws IOException {
//        设置生成图片的属性
        BufferedImage  bufferedImage = new BufferedImage(80,30,BufferedImage.TYPE_INT_RGB);
//        创建一个画笔
        Graphics2D gd = bufferedImage.createGraphics();
        gd.setColor(Color.WHITE);
        gd.drawRect(0,0,80,30);
        Font font = new Font("黑体",Font.BOLD,25);
        gd.setFont(font);
        StringBuilder vcode = new StringBuilder();
        for (int i=0;i<4;i++){
            String rdStr = String.valueOf(vcodeSequence[RandomUtil.randomInt(10)]) ;
            vcode.append(rdStr);
            //rgb
            gd.setColor(new Color(RandomUtil.randomInt(255),RandomUtil.randomInt(255),RandomUtil.randomInt(255)));
            gd.drawString(rdStr,(i+1)*15,25);
        }
        System.out.println(vcode);
        HttpSession session = req.getSession(true);
        session.setAttribute("session_vcode",vcode.toString());
//        设置http协议,图片类型
        resp.setContentType("image/jpeg");
        //不使用缓存
        resp.setDateHeader("Expires", -1);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setHeader("Pragma", "no-cache");

        ServletOutputStream sos = resp.getOutputStream();
        ImageIO.write(bufferedImage,"jpeg",sos);
        sos.flush();
        sos.close();
    }
    @RequestMapping("/checkVcode")
    @ResponseBody
    public ResponseResult checkVcode(String vcode,HttpSession session){
        System.out.println("我是效验验证码正不正确的");
        ResponseResult rr = new ResponseResult(-1,"验证码不正确");
        String session_vcode  = (String) session.getAttribute("session_vcode");
//        如果 是空的直接返回
        if (StrUtil.isEmpty(vcode) || StrUtil.isEmpty(session_vcode) ){
            return rr;
        }
        if (session_vcode.equals(vcode)){
            rr.setRcode(1);
            rr.setMessage("验证码正确");
        }
        return  rr;
    }
}
